const bcrypt = require("bcryptjs");
const { getUserInfo } = require("../service/user.service");
const {
  userFormateError,
  userAlreadyExited,
  userRegisterError,
  userNotExist,
  userLoginError,
  invalidPassword,
} = require("../constants/err.type");

const userValidator = async (ctx, next) => {
  // 合法性
  const { user_name, password } = ctx.request.body;
  if (!user_name || !password) {
    ctx.app.emit("error", userFormateError, ctx);
    return;
  }
  // 执行下一个中间件
  await next();
};

const verifyUser = async (ctx, next) => {
  // 合理性
  const { user_name } = ctx.request.body;
  try {
    const res = await getUserInfo({ user_name });
    // 判断是否已存在用户
    if (res) {
      console.error("用户名已经存在", user_name);
      ctx.app.emit("error", userAlreadyExited, ctx);
      return;
    }
  } catch (error) {
    ctx.app.emit("error", userRegisterError, ctx);
    return;
  }
  // 执行下一个中间件
  await next();
};

// 加密
const cryptPassword = async (ctx, next) => {
  const { password } = ctx.request.body;
  // 加盐
  var salt = bcrypt.genSaltSync(10);
  // 保存是密文
  var hash = bcrypt.hashSync(password, salt);

  ctx.request.body.password = hash;

  await next();
};

const verifyLogin = async (ctx, next) => {
  const { user_name, password } = ctx.request.body;
  try {
    // 1. 判断用户是否存在
    const res = await getUserInfo({ user_name });
    if (!res) {
      console.error("用户名不存在", user_name);
      ctx.app.emit("error", userNotExist, ctx);
      return;
    }

    // 2. 密码是否匹配
    if (!bcrypt.compareSync(password, res.password)) {
      ctx.app.emit("error", invalidPassword, ctx);
      return;
    }
  } catch (error) {
    ctx.app.emit("error", userLoginError, ctx);
    return;
  }

  await next();
};

module.exports = {
  userValidator,
  verifyUser,
  cryptPassword,
  verifyLogin,
};
